import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import * as d3 from 'd3'
import { progressApi } from '../services/api'
import type { ProgressOverview, VisualizationData, Achievement } from '../types'
import './ProgressMonitor.css'

interface ProgressMonitorProps {
  userId: string
}

const ProgressMonitor = ({ userId }: ProgressMonitorProps) => {
  const [overview, setOverview] = useState<ProgressOverview | null>(null)
  const [visualization, setVisualization] = useState<VisualizationData | null>(null)
  const [achievements, setAchievements] = useState<Achievement[]>([])
  const [weakness, setWeakness] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    loadData()
  }, [userId])

  const loadData = async () => {
    setIsLoading(true)
    try {
      // 设置超时，避免无限等待
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('加载超时')), 15000) // 15秒超时
      )
      
      const dataPromise = Promise.all([
        progressApi.getOverview(userId).catch(err => {
          console.warn('进度概览加载失败:', err)
          return null
        }),
        progressApi.getVisualizationData(userId).catch(err => {
          console.warn('可视化数据加载失败:', err)
          return null
        }),
        progressApi.getAchievements(userId).catch(err => {
          console.warn('成就数据加载失败:', err)
          return { achievements: [] }
        }),
        progressApi.getWeaknessAnalysis(userId).catch(err => {
          console.warn('薄弱环节分析加载失败:', err)
          return null
        }),
      ])
      
      const [overviewData, vizData, achievementsData, weaknessData] = await Promise.race([
        dataPromise,
        timeoutPromise
      ]) as any
      
      if (overviewData) setOverview(overviewData)
      if (vizData) setVisualization(vizData)
      if (achievementsData) setAchievements(achievementsData.achievements || [])
      if (weaknessData) setWeakness(weaknessData)
    } catch (error) {
      console.error('Failed to load progress data:', error)
      // 即使加载失败，也停止loading状态
    } finally {
      setIsLoading(false)
    }
  }

  useEffect(() => {
    if (visualization) {
      drawRadarChart(visualization.thinking_radar)
    }
  }, [visualization])

  const drawRadarChart = (radarData: VisualizationData['thinking_radar']) => {
    const svg = d3.select('#radar-chart')
    svg.selectAll('*').remove()

    const width = 400
    const height = 400
    const centerX = width / 2
    const centerY = height / 2
    const radius = Math.min(width, height) / 2 - 40

    const categories = Object.keys(radarData)
    const angleStep = (2 * Math.PI) / categories.length

    // 绘制网格
    const levels = 5
    for (let i = 1; i <= levels; i++) {
      const r = (radius * i) / levels
      svg
        .append('circle')
        .attr('cx', centerX)
        .attr('cy', centerY)
        .attr('r', r)
        .attr('fill', 'none')
        .attr('stroke', '#e0e0e0')
        .attr('stroke-width', 1)
    }

    // 绘制轴线
    categories.forEach((category, i) => {
      const angle = -Math.PI / 2 + angleStep * i
      const x = centerX + radius * Math.cos(angle)
      const y = centerY + radius * Math.sin(angle)
      svg
        .append('line')
        .attr('x1', centerX)
        .attr('y1', centerY)
        .attr('x2', x)
        .attr('y2', y)
        .attr('stroke', '#e0e0e0')
        .attr('stroke-width', 1)

      // 标签
      const labelX = centerX + (radius + 20) * Math.cos(angle)
      const labelY = centerY + (radius + 20) * Math.sin(angle)
      svg
        .append('text')
        .attr('x', labelX)
        .attr('y', labelY)
        .attr('text-anchor', 'middle')
        .attr('dominant-baseline', 'middle')
        .attr('font-size', '12px')
        .attr('fill', '#666')
        .text(category)
    })

    // 绘制数据
    const points = categories.map((category, i) => {
      const angle = -Math.PI / 2 + angleStep * i
      const value = radarData[category as keyof typeof radarData]
      const r = (radius * value) / 100
      return {
        x: centerX + r * Math.cos(angle),
        y: centerY + r * Math.sin(angle),
        value,
      }
    })

    // 绘制多边形
    const line = d3
      .line<{ x: number; y: number }>()
      .x((d) => d.x)
      .y((d) => d.y)
      .curve(d3.curveLinearClosed)

    svg
      .append('path')
      .datum(points)
      .attr('d', line)
      .attr('fill', 'rgba(102, 126, 234, 0.3)')
      .attr('stroke', '#667eea')
      .attr('stroke-width', 2)

    // 绘制点
    points.forEach((point) => {
      svg
        .append('circle')
        .attr('cx', point.x)
        .attr('cy', point.y)
        .attr('r', 4)
        .attr('fill', '#667eea')
    })
  }

  if (isLoading) {
    return (
      <div className="progress-monitor loading">
        <p>加载数据中...</p>
      </div>
    )
  }

  return (
    <div className="progress-monitor">
      {/* 概览卡片 */}
      {overview && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="overview-cards"
        >
          <div className="stat-card">
            <h3>学习天数</h3>
            <p className="stat-value">{overview.total_study_days}</p>
          </div>
          <div className="stat-card">
            <h3>学习时长</h3>
            <p className="stat-value">{overview.total_study_hours.toFixed(1)}h</p>
          </div>
          <div className="stat-card">
            <h3>答题总数</h3>
            <p className="stat-value">{overview.total_questions}</p>
          </div>
          <div className="stat-card">
            <h3>答对题数</h3>
            <p className="stat-value" style={{ color: '#10b981' }}>{overview.total_correct || 0}</p>
          </div>
          <div className="stat-card">
            <h3>答错题数</h3>
            <p className="stat-value" style={{ color: '#ef4444' }}>{overview.total_wrong || 0}</p>
          </div>
          <div className="stat-card">
            <h3>总体准确率</h3>
            <p className="stat-value">{overview.overall_accuracy.toFixed(1)}%</p>
          </div>
          <div className="stat-card">
            <h3>错误率</h3>
            <p className="stat-value" style={{ color: '#ef4444' }}>{overview.error_rate?.toFixed(1) || '0.0'}%</p>
          </div>
          <div className="stat-card">
            <h3>连续学习</h3>
            <p className="stat-value">{overview.current_streak}天</p>
          </div>
        </motion.div>
      )}
      
      {/* 薄弱环节分析 */}
      {weakness && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="weakness-card"
        >
          <h2>薄弱环节分析</h2>
          {weakness.weak_subjects && weakness.weak_subjects.length > 0 && (
            <div className="weakness-section">
              <h3>薄弱科目</h3>
              <ul>
                {weakness.weak_subjects.slice(0, 5).map((item: any, index: number) => (
                  <li key={index}>
                    <span className="subject-name">{item.subject}</span>
                    <span className="error-rate">错误率: {item.error_rate}%</span>
                    <span className="question-count">({item.wrong}/{item.total})</span>
                  </li>
                ))}
              </ul>
            </div>
          )}
          {weakness.weak_knowledge_points && weakness.weak_knowledge_points.length > 0 && (
            <div className="weakness-section">
              <h3>薄弱知识点</h3>
              <ul>
                {weakness.weak_knowledge_points.slice(0, 10).map((item: any, index: number) => (
                  <li key={index}>
                    <span className="knowledge-point">{item.knowledge_point}</span>
                    <span className="error-rate">错误率: {item.error_rate}%</span>
                    <span className="question-count">({item.wrong}/{item.total})</span>
                  </li>
                ))}
              </ul>
            </div>
          )}
          {weakness.recommendations && weakness.recommendations.length > 0 && (
            <div className="recommendations-section">
              <h3>改善建议</h3>
              <ul>
                {weakness.recommendations.map((rec: string, index: number) => (
                  <li key={index}>{rec}</li>
                ))}
              </ul>
            </div>
          )}
        </motion.div>
      )}

      {/* 思维雷达图 */}
      {visualization && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="chart-card"
        >
          <h2>思维能力雷达图</h2>
          <div className="chart-container">
            <svg id="radar-chart" width="400" height="400"></svg>
          </div>
        </motion.div>
      )}

      {/* 成就列表 */}
      {achievements.length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
          className="achievements-card"
        >
          <h2>成就徽章</h2>
          <div className="achievements-list">
            {achievements.map((achievement) => (
              <div key={achievement.achievement_id} className="achievement-item">
                <span className="achievement-icon">{achievement.icon}</span>
                <div className="achievement-info">
                  <h4>{achievement.name}</h4>
                  <p>{achievement.description}</p>
                </div>
              </div>
            ))}
          </div>
        </motion.div>
      )}
    </div>
  )
}

export default ProgressMonitor

